﻿using HBKY.Shop.Common;
using HBKY.Shop.Common.Helper;
using HBKY.Shop.Common.LogHelper;
using HBKY.Shop.Model;
using HBKY.Shop.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;

namespace HBKY.Shop.Extensions
{
    public static class QuartzJobExt
    {
        public static void UseQuartzJob(this IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
     {
            if (app == null) throw new ArgumentNullException(nameof(app));

            if (!Appsettings.Option("Middleware", "Job", "Enabled").ObjToBool()) return;

            ISchedulerCenter schedulerCenter = serviceProvider.GetService<ISchedulerCenter>();
            try
            {
                var allQzServices = Appsettings.Options<TaskJobListDto>("Middleware", "Job", "Jobs");
                foreach (var item in allQzServices)
                {
                    if (item.IsStart)
                    {
                        var success = schedulerCenter.AddScheduleJobAsync(item).Result;
                        if (success)
                        {
                            Console.WriteLine($"QuartzNetJob{item.Name}启动成功！");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManagerNlog.LogError(ex, "定时任务UseQuartzJob启动失败" + ex.Message);
            }
        }
    }
}
